<template>
  <view class="certification-page">
    <!-- 导航栏 -->
    <!-- <uni-nav-bar title="购买资格认证" left-icon="left" @clickLeft="goBack" background-color="#fff" color="#333" /> -->
    <CustomNavBar title="购买资格认证" backType="redirect" redirectUrl="/pages/activity/shared-pile/index" />
    <!-- 表单内容 -->
    <view class="form-container">
      <view class="form-section" :style="{borderBottom: 'none'}">
        <view class="section-title">身份信息实名</view>
        <view class="form-item">
          <view class="item-label">姓名</view>
          <input class="item-input" placeholder="请输入" v-model="formData.name" :disabled="isRealNameVerified" />
        </view>
        <view class="form-item">
          <view class="item-label">身份证号</view>
          <input class="item-input" placeholder="请输入" v-model="formData.idCard" :disabled="isRealNameVerified" />
        </view>
        <!-- <view class="item-label"></view> -->
      </view>
      <!-- 产权车位信息 -->
      <view class="form-section">
        <view class="section-title">产权车位信息</view>

        <view class="form-item" @click="showOwnershipPicker">
          <view class="item-label">车位归属</view>
          <view class="item-value">{{ formData.ownership }}</view>
          <uni-icons type="right" size="16" color="#999" />
        </view>

        <!-- 租赁车位时显示的额外字段 -->
        <template v-if="formData.ownership === '租赁车位'">
          <view class="form-item">
            <view class="item-label">产权人姓名</view>
            <input class="item-input" placeholder="请输入" v-model="formData.ownerName" />
          </view>

          <view class="form-item">
            <view class="item-label">产权人手机号</view>
            <input class="item-input" placeholder="请输入" v-model="formData.ownerPhone" />
          </view>
        </template>

        <view class="form-item">
          <view class="item-label">车位号</view>
          <input class="item-input" placeholder="请输入" v-model="formData.spaceNo" />
        </view>
        
        <view class="form-item" @click="showLocationPicker">
          <view class="item-label">所在位置</view>
          <view class="item-value">{{ formData.position }}</view>
          <uni-icons type="right" size="16" color="#999" />
        </view>

        <view class="form-item">
          <view class="item-label">上传合同照片/产权证</view>
        </view>
        <view class="upload-container">
          <view class="upload-item image-text" @click="chooseImage('contract')">
            <image v-if="formData.contractImageUrl" :src="formData.contractImageUrl" class="uploaded-image" mode="aspectFill" />
            <view v-else class="upload-placeholder">
              <!-- <image src="/static/images/activity_pile/upload1.png" class="upload-icon" mode="aspectFit" /> -->
              <text class="upload-text">请上传</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 共享车辆信息 -->
      <view class="form-section">
        <view class="section-title">共享车辆信息</view>

        <view class="form-item">
          <view class="item-label">车牌号</view>
          <input class="item-input" placeholder="请输入" v-model="formData.plate" />
        </view>

        <view class="form-item">
          <view class="item-label">车辆vin码 <uni-icons type="help" size="20" color="#dedede" style=" border-radius: 50%; padding: 2rpx;" /></view>

          <!-- <view class="item-info">

          </view> -->
          <input class="item-input" placeholder="请输入" v-model="formData.vin" />
        </view>

        <view class="form-item">
          <view class="item-label">行驶证</view>
        </view>
        <view class="upload-container">
          <view class="upload-item image-license" @click="chooseImage('license')">
            <image v-if="formData.licenseImageUrl" :src="formData.licenseImageUrl" class="uploaded-image" mode="aspectFill" />
            <view v-else class="upload-placeholder">
              <!-- <image src="/static/images/activity_pile/upload2.png" class="upload-icon" mode="aspectFit" /> -->
              <text class="upload-text">请上传</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 充电机信息 -->
      <view class="form-section">
        <view class="section-title">充电桩信息</view>

        <view class="form-item">
          <view class="item-label">请上传充电桩照片</view>
        </view>
        <view class="upload-container">
          <view class="upload-item image-charger" @click="chooseImage('charger')">
            <image v-if="formData.chargerImageUrl" :src="formData.chargerImageUrl" class="uploaded-image" mode="aspectFill" />
            <view v-else class="upload-placeholder">
              <!-- <image src="/static/images/activity_pile/upload1.png" class="upload-icon" mode="aspectFit" /> -->
              <text class="upload-text">请上传</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 购买资格说明 -->
      <view class="qualification-section">
        <view class="qualification-title">购买资格</view>
        <view class="qualification-subtitle">三个条件同时具备的仅限购买一台</view>

        <view class="qualification-item">
          <view class="qualification-number">1.</view>
          <view class="qualification-content">
            <view class="qualification-main">有产权车位（前提条件）</view>
          </view>
        </view>

        <view class="qualification-item">
          <view class="qualification-number">2.</view>
          <view class="qualification-content">
            <view class="qualification-main">有汽车</view>
            <view class="qualification-desc">7座以下新能源汽车或燃油汽车，电摩车不限购一台</view>
          </view>
        </view>

        <view class="qualification-item">
          <view class="qualification-number">3.</view>
          <view class="qualification-content">
            <view class="qualification-main">已安装充电桩</view>
            <view class="qualification-desc">已申请并安装充电桩的用户可购买个人充电桩</view>
             <view class="qualification-buy">*仅限合肥市区符合上述条件的用户购买</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部认证按钮 -->
    <view class="bottom-action">
      <button class="cert-button" @click="submitCertification">认证并绑定车辆</button>
    </view>

    <!-- 车位归属选择弹窗 -->
    <view v-if="showOwnershipModal" class="modal-overlay" @click="hideOwnershipPicker">
      <view class="ownership-modal" @click.stop>
        <!-- <view class="modal-header">
          <text class="modal-title">选择车位归属</text>
          
        </view> -->
        <view class="modal-content">
          <view
            class="ownership-option"
            v-for="(option, index) in ownershipOptions"
            :key="index"
            @click="selectOwnership(option)"
          >
            <text class="option-text">{{ option }}</text>
          </view>
        </view>
        <view class="modal-footer">
          <view class="cancel-btn" @click="hideOwnershipPicker">
            <text class="cancel-text">取消</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 所在位置选择弹窗 -->
    <view v-if="showLocationModal" class="modal-overlay" @click="hideLocationPicker">
      <view class="ownership-modal" @click.stop>
        <view class="modal-content">
          <view
            class="ownership-option"
            v-for="(option, index) in locationOptions"
            :key="index"
            @click="selectLocation(option)"
          >
            <text class="option-text">{{ option }}</text>
          </view>
        </view>
        <view class="modal-footer">
          <view class="cancel-btn" @click="hideLocationPicker">
            <text class="cancel-text">取消</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import CustomNavBar from '@/components/CustomNavBar.vue'
import PileApi from '@/api/pile/pile.js'
import HomeApi from '@/api/app/home.js'
import { uploadFile } from '@/api/util.js'

// 表单数据
const formData = ref({
  name: '',
  idCard: '',
  ownership: '本人车位',
  ownerName: '',
  ownerPhone: '',
  spaceNo: '',
  propertyAddress: '',
  position: '地上', // 地上或地下
  contractImageUrl: '',
  plate: '',
  vin: '',
  vehicleOwner: '',
  licenseImageUrl: '',
  chargerImageUrl: ''
})

// 用户实名认证状态
const isRealNameVerified = ref(false)

// 车位归属选项
const ownershipOptions = ['本人车位', '租赁车位']

// 所在位置选项
const locationOptions = ['地上', '地下']

// 弹窗显示状态
const showOwnershipModal = ref(false)
const showLocationModal = ref(false)

// 页面加载时获取用户信息
onMounted(async () => {
  try {
    const userInfo = await HomeApi.getMyInfo()
    if (userInfo && userInfo.data) {
      const { realAuth, identity, realName } = userInfo.data
      
      // 如果已实名认证(realAuth为0)，则填充信息并禁用输入框
      if (realAuth === 0) {
        formData.value.name = realName || ''
        formData.value.idCard = identity || ''
        isRealNameVerified.value = true
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
})

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 显示车位归属选择器
const showOwnershipPicker = () => {
  showOwnershipModal.value = true
}

// 隐藏车位归属选择器
const hideOwnershipPicker = () => {
  showOwnershipModal.value = false
}

// 选择车位归属
const selectOwnership = (option) => {
  formData.value.ownership = option
  // 切换到本人车位时清空租赁相关字段
  if (formData.value.ownership === '本人车位') {
    formData.value.ownerName = ''
    formData.value.ownerPhone = ''
  }
  hideOwnershipPicker()
}

// 显示所在位置选择器
const showLocationPicker = () => {
  showLocationModal.value = true
}

// 隐藏所在位置选择器
const hideLocationPicker = () => {
  showLocationModal.value = false
}

// 选择所在位置
const selectLocation = (option) => {
  formData.value.position = option
  hideLocationPicker()
}

// 选择图片
const chooseImage = async (type) => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    // 限制只能选择图片文件
    extension: ['jpg', 'jpeg', 'png', 'webp', 'bmp'],
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0]
      const fileSize = res.tempFiles[0].size // 获取文件大小（字节）
      
      // 检查文件大小（限制为5MB）
      const maxSize = 5 * 1024 * 1024 // 5MB转换为字节
      if (fileSize > maxSize) {
        uni.showToast({
          title: '图片大小不能超过5MB',
          icon: 'none'
        })
        return
      }
      
      // 显示上传进度
      uni.showLoading({
        title: '上传中...'
      })
      
      try {
        // 获取原始文件名（从路径中提取）
        const pathParts = tempFilePath.split('/')
        const originalFileName = pathParts[pathParts.length - 1] || 'image.jpg'
        
        // 根据类型设置不同的文件前缀
        let prefix = 'image'
        if (type === 'contract') {
          prefix = 'contract'
        } else if (type === 'license') {
          prefix = 'license'
        } else if (type === 'charger') {
          prefix = 'charger'
        }
        
        // 上传文件到OSS，启用图片限制
        const result = await uploadFile(
          tempFilePath,
          'pile', // 模块名称
          originalFileName,
          prefix,
          (progress) => {
            // 更新上传进度
            uni.showLoading({
              title: `上传中...${progress}%`
            })
          },
          true, // 启用图片限制
          5 // 最大文件大小5MB
        )
        
        // 上传成功，设置图片URL
        if (type === 'contract') {
          formData.value.contractImageUrl = result.url
        } else if (type === 'license') {
          formData.value.licenseImageUrl = result.url
        } else if (type === 'charger') {
          formData.value.chargerImageUrl = result.url
        }
        
        uni.hideLoading()
        uni.showToast({
          title: '上传成功',
          icon: 'success'
        })
        
      } catch (error) {
        console.error('上传失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: error.message || '上传失败，请重试',
          icon: 'none'
        })
      }
    },
    fail: (err) => {
      console.error('选择图片失败:', err)
      uni.showToast({
        title: '选择图片失败',
        icon: 'none'
      })
    }
  })
}

// 提交认证
const submitCertification = async () => {
  // 验证基本表单字段
  if (!formData.value.name) {
    uni.showToast({
      title: '请输入姓名',
      icon: 'none'
    })
    return
  }

  if (!formData.value.idCard) {
    uni.showToast({
      title: '请输入身份证号',
      icon: 'none'
    })
    return
  }

  // 验证身份证号格式
  const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  if (!idCardReg.test(formData.value.idCard)) {
    uni.showToast({
      title: '请输入正确的身份证号',
      icon: 'none'
    })
    return
  }

  if (formData.value.ownership === '租赁车位') {
    if (!formData.value.ownerName) {
      uni.showToast({
        title: '请输入产权人姓名',
        icon: 'none'
      })
      return
    }

    if (!formData.value.ownerPhone) {
      uni.showToast({
        title: '请输入产权人手机号',
        icon: 'none'
      })
      return
    }
  }

  if (!formData.value.spaceNo) {
    uni.showToast({
      title: '请输入车位号',
      icon: 'none'
    })
    return
  }

  if (!formData.value.plate) {
    uni.showToast({
      title: '请输入车牌号',
      icon: 'none'
    })
    return
  }

  if (!formData.value.vin) {
    uni.showToast({
      title: '请输入车辆VIN码',
      icon: 'none'
    })
    return
  }

  if (!formData.value.contractImageUrl) {
    uni.showToast({
      title: '请上传合同照片/产权证',
      icon: 'none'
    })
    return
  }

  if (!formData.value.licenseImageUrl) {
    uni.showToast({
      title: '请上传行驶证',
      icon: 'none'
    })
    return
  }

  if (!formData.value.chargerImageUrl) {
    uni.showToast({
      title: '请上传充电机照片',
      icon: 'none'
    })
    return
  }

  try {
    // 检查实名认证状态
    if (!isRealNameVerified.value) {
      // 显示实名认证loading
      uni.showLoading({
        title: '正在实名认证'
      })
      try {
        // 提交实名认证
        const realNameResult = await HomeApi.submitRealNameVerification(formData.value.name, formData.value.idCard)
        console.log('实名认证结果:', realNameResult)
        // 等待接口返回后再隐藏loading
        uni.hideLoading()
        if (realNameResult) { 
          // 实名认证成功，更新状态并禁用输入框
          isRealNameVerified.value = true
        } else {
          // 实名认证失败
          uni.showToast({
            title: realNameResult?.message || '实名认证未通过',
            icon: 'none'
          })
          return
        }
      } catch (realNameError) {
        console.error('实名认证失败:', realNameError)
        // 等待接口返回后再隐藏loading
        uni.hideLoading()
        uni.showToast({
          title: realNameError?.message || '实名认证未通过',
          icon: 'none'
        })
        return
      }
    } else {
      // 已实名认证，再次验证状态
      try {
        const verificationResult = await HomeApi.getRealNameVerification()
        console.log('实名认证状态验证结果:', verificationResult)
        if (!verificationResult) {
          uni.showToast({
            title: '实名认证未通过',
            icon: 'none'
          })
          return
        }
      } catch (verifyError) {
        console.error('验证实名认证状态失败:', verifyError)
        uni.showToast({
          title: '实名认证未通过',
          icon: 'none'
        })
        return
      }
    }

    // 实名认证通过，继续提交认证数据
    uni.showLoading({
      title: '提交中...'
    })
    // return; 测试实名认证提交
    // 准备提交数据
    const certData = {
      parkingOwnership: formData.value.ownership === '本人车位' ? 0 : 1, // 0-本人车位，1-租赁车位
      ownerName: formData.value.ownerName || '',
      ownerPhone: formData.value.ownerPhone || '',
      spaceNo: formData.value.spaceNo, // 车位号
      position: formData.value.position === '地上' ? 0 : 1, // 0-地上，1-地下
      plate: formData.value.plate,
      vin: formData.value.vin, // 车辆VIN码
      // 图片URL已经在chooseImage方法中上传并设置，直接使用
      contractImageUrl: formData.value.contractImageUrl,
      licenseImageUrl: formData.value.licenseImageUrl,
      chargerImageUrl: formData.value.chargerImageUrl
    }
    
    // 提交认证数据
    console.log('提交认证数据:', certData);
    const result = await PileApi.submitCertification(certData)
    console.log('提交认证结果:', result);
    // 隐藏加载提示
    uni.hideLoading()
    
    if (result > 0) {
      uni.showToast({
        title: '认证提交成功',
        icon: 'success'
      })
      
      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateTo({ url: "/pages/activity/shared-pile/index" })
      }, 1000)
    } else {
      uni.showToast({
        title: result?.message || '认证提交失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('认证提交失败:', error)
    uni.hideLoading()
    uni.showToast({
      title: '认证提交失败，请重试',
      icon: 'none'
    })
  }
}
</script>

<style scoped>
.certification-page {
  background-color: #fff;
  min-height: 100vh;
}

.form-container {
  padding: 20rpx;
}

.form-section {
  background-color: #fff;
  /* border-radius: 16rpx; */
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 30rpx;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

/* 只在产权车位信息、共享车辆信息和充电桩信息模块中移除最后一个form-item的底部边框 */
.form-section:not(:first-child) .form-item:last-child {
  border-bottom: none;
}

.item-label {
  font-size: 28rpx;
  color: #333;
  width: 300rpx;
  flex-shrink: 0;
}

.item-value {
  font-size: 30rpx;
  color: black;
  flex: 1;
  text-align: right;
}

.item-input {
  font-size: 28rpx;
  color: #333;
  flex: 1;
  text-align: right;
}

.item-info {
  margin-left: 10rpx;
}

.upload-container {
  padding: 30rpx 100rpx 0 110rpx;
  position: relative;
}

.upload-item {
  width: 450rpx;
  height: 250rpx;
  border: 2rpx dashed #ddd;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;

}
.image-text{
    background-image: url('https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/images/activity_pile/upload1.png');
    background-size: 100% 100%;
    background-position: center;
    background-repeat: no-repeat;
    z-index: 0;

}
.image-license{
    background-image: url('https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/images/activity_pile/upload2.png');
    background-size: 100% 100%;
    background-position: center;
    background-repeat: no-repeat;
}
.image-charger{
    background-image: url('https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/images/activity_pile/upload3.png');
    background-size: 100% 100%;
    background-position: center;
    background-repeat: no-repeat;
}
.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.upload-icon {
  width: 60rpx;
  height: 60rpx;
  margin-bottom: 10rpx;
}

.upload-text {
  font-size: 24rpx;
  color: #fff;
  z-index:1;
  padding-top: 120rpx;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  border-radius: 10rpx;
}

.qualification-section {
  background-image: url('https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/images/activity_pile/bg8.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 120rpx;
}

.qualification-title {
  font-size: 35rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 10rpx;
  text-align: center;
}

.qualification-subtitle {
  font-size: 24rpx;
  color: black;
  margin-bottom: 30rpx;
  text-align: center;
}

.qualification-item {
  display: flex;
  margin-bottom: 30rpx;
}

.qualification-number {
  font-size: 28rpx;
  color: #ff6b35;
  font-weight: 600;
  width: 40rpx;
  flex-shrink: 0;
}

.qualification-content {
  flex: 1;
}

.qualification-main {
  font-size: 28rpx;
  color: #ff6b35;
  font-weight: 550;
  margin-bottom: 8rpx;
  letter-spacing: 1rpx;
}

.qualification-desc {
  font-size: 24rpx;
  color: black;
  line-height: 1.5;
  letter-spacing: 1rpx;
}
.qualification-buy{
    font-size: 20rpx;
    color: gray;
    /* font-weight: 550; */
    margin-top: 15rpx;
    letter-spacing: 1rpx;
}
.car-image-container {
  display: flex;
  justify-content: center;
  margin-top: 30rpx;
}

.car-image {
  width: 300rpx;
  height: 200rpx;
}

.bottom-action {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx;
  /* box-shadow: 0 -2rpx 20rpx rgba(0, 0, 0, 0.1); */
}

.cert-button {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(90deg, #00D4AA 0%, #00C896 100%);
  border-radius: 44rpx;
  border: none;
  font-size: 32rpx;
  font-weight: 600;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cert-button:active {
  opacity: 0.8;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: flex-end;
}

.ownership-modal {
  width: 100%;
  background-color: #fff;
  border-top-left-radius: 15px;
  border-top-right-radius: 15px;
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.modal-header {
  padding: 40rpx 0 20rpx 0;
  text-align: center;
  /* border-bottom: 1rpx solid #f0f0f0; */
  position: relative;
}

.modal-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.modal-content {
  padding: 0;
}

.ownership-option {
  padding: 40rpx 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
  /* display: flex; */
  align-items: center;
  text-align: center;
}

.ownership-option:last-child {
  border-bottom: none;
  padding-bottom: 40rpx;
}

.option-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.ownership-option:active {
  background-color: #f5f5f5;
}

.close-btn {
  position: absolute;
  top: 20rpx;
  right: 30rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  /* border-radius: 50%;
  background-color: #f5f5f5; */
}

.close-icon {
  font-size: 50rpx;
  color: #979797;
  /* line-height: 1; */
}

.close-btn:active {
  background-color: #e0e0e0;
}

.modal-footer {
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
}

.cancel-btn {
  width: 100%;
  height: 88rpx;
  background-color: #EFEFEF;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cancel-text {
  font-size: 32rpx;
  color: black;
  font-weight: 500;
}

.cancel-btn:active {
  background-color: #e8e8e8;
}

/* 单选按钮样式 */
.radio-group {
  display: flex;
  flex-direction: row;
}

.radio-item {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 160rpx;
  height: 70rpx;
  border-radius: 35rpx;
  background-color: #f5f5f5;
  margin-right: 30rpx;
}

.radio-item.active {
  background-color: #007aff;
}

.radio-text {
  font-size: 28rpx;
  color: #333;
}

.radio-item.active .radio-text {
  color: #fff;
}
</style>
